//
//  LYIntroduceController.m
//  LYLiveApp
//
//  Created by QD on 16/8/25.
//  Copyright © 2016年 览益信息科技. All rights reserved.
//

#import "LYIntroduceController.h"
#import "LYActivityModel.h"
#import "LYLiveUnPlayingCell.h"
#import "LYLivePlayingCell.h"
#import "LYNTESController.h"
#import "LYLiveWaitCell.h"

static const NSInteger      kEstimatedRowHeight  = 90.0f ;

@interface LYIntroduceController ()
<UITableViewDelegate,
UITableViewDataSource,
RequestDelegate
>

@property (weak, nonatomic) IBOutlet UITableView *introduceTable;
@property (nonatomic,strong) UILabel * markLbl;
@property(nonatomic,strong) NSMutableArray *dataArray;
@property(nonatomic,strong) LYLivePlayingCell *playingCell;
@property(nonatomic,assign) NSInteger indexProgram;
@property(nonatomic,strong) LYRoomListModel *listModel;
@end

@implementation LYIntroduceController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    self.introduceTable.estimatedRowHeight = kEstimatedRowHeight;
    self.introduceTable.rowHeight = UITableViewAutomaticDimension;
    
    WS(weakSelf)
    [self.introduceService loadRoomList:nil block:^(BOOL success, NSMutableArray *object) {
        if (success) {
            
            if (self.introduceBlock && [LYLocalData sharedInstance].roomInfo) {
                self.introduceBlock([LYLocalData sharedInstance].roomInfo);
            }
            if (object.count) {
                
                if ([LYLocalData sharedInstance].roomInfo.living.integerValue == 1) {
                    for (int i = 0; i < object.count; i ++) {
                        LYLog(@"111111111111111111111111");
                        LYRoomListModel *model = object[i];
                        if (model.actStatus.integerValue == 1) {
                            LYLog(@"2222222222222222222222");
                            weakSelf.indexProgram  = i;
                            LYLog(@"weakSelf.indexProgram %ld",weakSelf.indexProgram);
                            break;
                        } else {
                            if (model.actStatus.integerValue == 0) {
                                [object insertObject:weakSelf.listModel atIndex:i];
                                LYLog(@"333333333333333333333333");
                                break;
                            }
                        }
                    }
                }
                
                weakSelf.dataArray = [NSMutableArray arrayWithArray:object];
               
                [object enumerateObjectsUsingBlock:^(LYRoomListModel *model, NSUInteger index, BOOL * _Nonnull stop) {
                    if (model.actStatus.integerValue == 1 && index != 0) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [weakSelf.introduceTable reloadData];
                            [weakSelf.introduceTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
                        });
                    }
                }];

            } else {
               
                weakSelf.introduceTable.hidden = YES;
                UILabel *upLabel = [[UILabel alloc] init];
                upLabel.frame = CGRectMake(0, 68, SCREEN_WIDTH, 22);
                upLabel.textAlignment = NSTextAlignmentCenter;
                upLabel.textColor = HEX(@"#929292");
                upLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:16.0f];
                upLabel.text = @"今日休息,暂无直播";
                [weakSelf.view addSubview:upLabel];
                
                UILabel *subLabel = [[UILabel alloc] init];
                subLabel.frame = CGRectMake(0, 100, SCREEN_WIDTH, 21);
                subLabel.textAlignment = NSTextAlignmentCenter;
                subLabel.textColor = HEX(@"#b8b8b8");
                subLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15.0f];
                subLabel.text = @"具体直播时间,请留意相关公告";
                [weakSelf.view addSubview:subLabel];
            }
            
            [weakSelf.introduceTable reloadData];
        }
        
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(timeTableDataChange:) name:kWebSocketLiveTimeTableDataUpdate object:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
}

- (void)timeTableDataChange:(NSNotification *)notify {
    
    WS(weakSelf)
    NSDictionary *userInfo = notify.userInfo;
    NSNumber *schedule = userInfo[@"schedule"];
    
    if ([weakSelf.dataArray containsObject:weakSelf.listModel]) {
        [weakSelf.dataArray removeObject:weakSelf.listModel];
    }

    NSInteger sizeProgram = self.dataArray.count;
    NSInteger indexProgram = sizeProgram;
    for (int i = 0; i < sizeProgram; i++) {
        LYRoomListModel *model = self.dataArray[i];
        if (model.actId.integerValue == schedule.integerValue) {
            indexProgram = i;
            self.indexProgram = indexProgram;
        }
        
        if (schedule.integerValue == 0) {
            indexProgram = self.indexProgram;
            if (i < indexProgram + 1) {
              
                model.actStatus = @(3);
                
            } else if (i == indexProgram + 1) {
                
                if ([LYLocalData sharedInstance].roomInfo.living.integerValue == 1) {
                    [self.dataArray insertObject:weakSelf.listModel atIndex:i];
                }
                
            } else if (i > indexProgram +1) {
                model.actStatus = @(0);
            }

        } else {
            if (i < indexProgram) {
                model.actStatus = @(3);
            } else if (i == indexProgram) {
                model.actStatus = @(1);
            } else if (i > indexProgram) {
                model.actStatus = @(0);
            }
        }
        
    }
    
    [weakSelf.introduceTable reloadData];
}

#pragma mark - ******** 离开直播页面时销毁定时器 快捷键为mark
- (void)dealloc
{
    LYLog(@"%s",__FUNCTION__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - RequestDelegate
-(void) eventRequestSuccess:(id)obj{

}

-(void) eventRequestError:(id)obj{
    
    [LYUtil hideHUDTo:self.view];
    [self _endRefreshing];
}

-(void) eventRequestBegining:(id)obj{
    
    [LYUtil showProgressHUDAddedTo:self.view];
}

-(void)_endRefreshing
{
    
}

#pragma mark ------ UITableViewDataSource && Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WS(weakSelf)
    
    if (self.dataArray.count) {
        LYRoomListModel *model = self.dataArray[indexPath.row];
        if (model.actStatus.integerValue == 1) {
            if (model.actType.integerValue == 2) {
                LYLiveWaitCell *cell = [LYLiveWaitCell cellWithTableView:tableView];
                cell.roomListModel = model;
                cell.videoLiveBlock = ^(LYRoomListModel *listModel) {
                    !weakSelf.videoLiveBlock?:weakSelf.videoLiveBlock();
                    for (LYRoomListModel *model in weakSelf.dataArray) {
                        model.isPlaybacking = NO;
                        model.isPlayLiving = NO;
                    }
                    listModel.isPlayLiving = YES;
                    [weakSelf.introduceTable reloadData];
                };
                cell.joinTeamBlock = ^{
                    LYNTESController *ntesVC = [[LYNTESController alloc] initWithNibName:@"LYNTESController" bundle:nil];
                    ntesVC.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:ntesVC animated:YES];
                };

                return cell;
            } else {
                LYLivePlayingCell *cell = [LYLivePlayingCell cellWithTableView:tableView];
                cell.videoLiveBlock = ^(LYRoomListModel *listModel){
                    !weakSelf.videoLiveBlock?:weakSelf.videoLiveBlock();
                    for (LYRoomListModel *model in weakSelf.dataArray) {
                        model.isPlaybacking = NO;
                        model.isPlayLiving = NO;
                    }
                    listModel.isPlayLiving = YES;
                    [weakSelf.introduceTable reloadData];
                };
                cell.roomListModel = model;
                cell.joinTeamBlock = ^{
                    LYNTESController *ntesVC = [[LYNTESController alloc] initWithNibName:@"LYNTESController" bundle:nil];
                    ntesVC.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:ntesVC animated:YES];
                };
                return cell;
            }
        } else {
            
            if (model.actType.integerValue == 2) {
                static NSString *identify =@"cellIdentify";
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
                if(!cell) {
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identify];
                }
                return cell;
            } else {
                LYLiveUnPlayingCell *cell = [LYLiveUnPlayingCell cellWithTableView:tableView];
                cell.playBackBlock = ^(LYRoomListModel *listModel) {
                    
                    NSDictionary *parameters = @{@"actId":@(listModel.actId.integerValue)};
                    [weakSelf.introduceService checkPlayBackState:parameters block:^(BOOL success, id object) {
                        if (success) {
                            weakSelf.playingCell.roomListModel.isPlayLiving = NO;
                            !weakSelf.playBackBlock?:weakSelf.playBackBlock(listModel);
                            for (LYRoomListModel *model in weakSelf.dataArray) {
                                model.isPlaybacking = NO;
                                model.isPlayLiving = NO;
                            }
                            listModel.isPlaybacking = YES;
                            [weakSelf.introduceTable reloadData];
                        } else {
                            [LYUtil showLongTextFailedHUD:@"回看生成中,请稍后尝试" AddedTo:MAIN_WINDOW interval:1.0f];
                        }
                    }];
                    
                };
                cell.expandBlock = ^{
                    [weakSelf.introduceTable reloadData];
                };
                cell.roomListModel = model;
                return cell;
            }
        }
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.dataArray.count) {
        LYRoomListModel *model = self.dataArray[indexPath.row];
        if (model.actStatus.integerValue == 1) {
            return [LYRoomListModel returnRowHeightWithModel:model];
        } else {
            if (model.actType.integerValue == 2) {
                return 0;
            } else {
                if (model.isExpand) {
                    return [LYRoomListModel returnRowHeightWithModel:model];
                } else {
                    return 60;
                }
            }
        }
    } else {
        return 0;
    }
}


#pragma mark - ******** getter & setter 快捷键为mark
-(LYIntroduceService *)introduceService{
    
    if (nil == _introduceService) {
        _introduceService = [[LYIntroduceService alloc] initWithDelegate:self];
    }
    return _introduceService;
}

- (LYRoomListModel *)listModel {
    
    if (nil == _listModel) {
        _listModel = [LYRoomListModel new];
        _listModel.actType = [NSNumber numberWithInt:2];
        _listModel.actStatus = [NSNumber numberWithInt:1];
        _listModel.actName = @"正在播放片花";
        _listModel.isPlayLiving = YES;
    }
    return _listModel;
}
@end
